package com.igeek.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.igeek.domain.User;
import com.igeek.service.OrderitemService;
import com.igeek.service.UserService;
import com.igeek.utils.Result;
import com.igeek.utils.SendSMS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author spike
 * @since 2022-01-12
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderitemService orderitemService;
    /*var params = "/"+$("#mobile").val()+"/"+$("#kapcode").val()+"/"+$("#pwd").val();
		$.post(
			"sms_regist"+params,*/
    //短信注册
    @PostMapping("/sms_regist/{mobile}/{kapcode}/{pwd}")
    public Result mobile_regist(@PathVariable("mobile") String mobile,
                                @PathVariable("kapcode") String kapcode,
                                @PathVariable("pwd") String pwd,
                                HttpSession session){
        log.info("mobile:"+mobile+"-"+kapcode+"-"+pwd);
        //1.判断验证码是否正确
        String code = (String) session.getAttribute("code");
        if(kapcode.equals(code)){
            //2.把用户名和密码放入数据表
            User user = new User(mobile,pwd);
            return  regist_(user);

        }else{
            return Result.fail("验证码不正确");
        }
    }

    //接收验证码请求
    @GetMapping("/sms/{mobile}")
    public Result sendSms(@PathVariable("mobile") String mobile,HttpSession session) throws Exception {
        String code =  SendSMS.send(mobile);
        session.setAttribute("code",code);
        //把验证码放入session中
        return Result.success(code);
    }
    //forelogin
    @PostMapping("/forelogin")
    public Result login(@Valid @RequestBody User user, HttpSession session){
//        if(user == null) return Result.fail("用户名或密码不能为空...");
//        if(user.getName().equals("") || user.getPassword().equals("")) return Result.fail("用户名或密码不能为空...");

        //1.根据用户名拿到盐
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",user.getName());
        User user1 = userService.getOne(wrapper);
        if(user1 == null) return Result.fail("用户名或密码不存在");
        //2.对密码进行加盐加密
        String md5Pwd =DigestUtils.md5DigestAsHex((user.getPassword()+user1.getSalt()).getBytes());
        user.setPassword(md5Pwd);
        //3.判断用户名和密码是否正确
        wrapper = new QueryWrapper<>();
        wrapper.eq("name",user.getName())
                .eq("password",user.getPassword());
        User user2 =userService.getOne(wrapper);
        if(user2 == null){
            return Result.fail("用户名或密码不存在");
        }else{
            //把user2存入session
            session.setAttribute("user",user2);
            //统计购物车数量 session.cartTotalItemNumber
            int count = orderitemService.getCartNumber(user2);
            session.setAttribute("cartTotalItemNumber",count);
            String path = (String) session.getAttribute("currentPath");
            return Result.success(path);
        }

    }

    //http://localhost:8080/foreregister
    @PostMapping("/foreregister")
    public Result regist(@RequestBody User user){
        log.info("user:"+user);
        return regist_(user);
    }

    private Result regist_(@RequestBody User user) {
        //1.判断用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",user.getName());
        User user1 = userService.getOne(wrapper);
        if(user1 !=null){//用户已存在
            return  Result.fail("用户已存在");
        }else{
            //2.保存用户
            //对user进行加盐加密
            //盐是随机数    63a9f0ea7bb98050796b649e85481845
            String salt = UUID.randomUUID().toString();
            //12363a9f0ea7bb98050796b649e85481845
            String md5Pwd = user.getPassword()+salt;
            //MD5加密
            md5Pwd= DigestUtils.md5DigestAsHex(md5Pwd.getBytes());
            user.setPassword(md5Pwd);
            user.setSalt(salt);
            userService.save(user);
            return Result.success();
        }
    }

}

